﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using Repetition.Domain;
using NHibernate.Criterion;

namespace Repetition.Persistence.NHibernate
{
    public class SubjectRepository : Repository<Subject>, ISubjectRepository
    {
        public SubjectRepository()
            : base() { }

        public SubjectRepository(ISession session)
            : base(session) { }

        public void RemoveSubjectAndOrphanProblems(Subject subject)
        {
            using (ITransaction transaction = Session.BeginTransaction())
            {
                ICollection<Problem> problems =
                    Session.CreateCriteria(typeof(Problem)).CreateCriteria("Subjects")
                        .Add(Expression.Eq("Name", subject.Name))
                        .List<Problem>();

                foreach (Problem problem in problems)
                {
                    problem.RemoveSubject(subject);

                    if (problem.Subjects.Count == 0)
                        Session.Delete(problem);
                }

                Session.Delete(subject);

                transaction.Commit();
            }
        }
    }
}
